#!/usr/bin/env python
# -*- coding: utf-8 -*-
#================================#
# @author: RedSoxFan and NerfSoldier
# @copyright: 2012 RedSoxFan and NerfSoldier
# @license: GNU General Public License v3.0 
#           <http://www.gnu.org/copyleft/gpl.html>
# @summary: Java Interface Template
#=======================================#

#=======================================#
# Imports
#=======================================#
# Python
import getpass
import os
from PyQt4 import QtCore, QtGui
import re
import time
# DarkDev
from templates import Template
#=======================================#
class Validator(QtGui.QValidator):
    def __init__(self):
        QtGui.QValidator.__init__(self)
    def validate(self, inp, pos):
        if re.match("^[A-Z_][A-Za-z0-9_]*$",str(inp)):
            return (QtGui.QValidator.Acceptable,pos)
        if not str(inp):
            return (QtGui.QValidator.Intermediate,pos)
        return (QtGui.QValidator.Invalid,pos)
class Javainterface(Template):
    name = 'Java Interface'
    def show(self,folder):
        fields = {'folder':folder}
        # Create Dialog
        diag = QtGui.QDialog(self.darkdev)
        diag.setWindowTitle("Create Interface")
        # Create GridLayout
        grid = QtGui.QGridLayout(diag)
        row = 0
        # Add Package Label
        fields['package'] = folder[folder.rfind('src')+4:].replace("\\",".").replace("/",".")
        grid.addWidget(QtGui.QLabel('Package: <i>%s</i>'%(fields['package'] or "&lt;default&gt;")),row,0)
        row+=1
        # Add Package Name Label
        cn = QtGui.QLabel("Package Name:")
        cn.setToolTip("Start With An Uppercase Letter or Underscore\nAdd Letters, Numbers, and/or Underscores")
        grid.addWidget(cn,row,0)
        row+=1
        # Add Package Name LineEdit (Only Accepts Proper Naming Convention)
        fields['name'] = QtGui.QLineEdit()
        fields['name'].setValidator(Validator())
        grid.addWidget(fields['name'],row,0)
        row+=1
        # Add Visibility Label
        grid.addWidget(QtGui.QLabel("Visibility:"),row,0)
        row+=1
        # Add Visibility Modifiers
        vmodgr = QtGui.QGridLayout()
        visgrp = QtGui.QButtonGroup()
        for i,m in enumerate(['default','public']):
            fields['vis.%s'%m] = QtGui.QRadioButton(m)
            visgrp.addButton(fields['vis.%s'%m])
            if m=='public': fields['vis.%s'%m].setChecked(True)
            vmodgr.addWidget(fields['vis.%s'%m],0,i)
        grid.addLayout(vmodgr,row,0)
        row+=1
        # Add Options Label
        grid.addWidget(QtGui.QLabel("Options:"),row,0)
        row+=1
        # Add Options
        for m,c in [('Add JavaDoc',True)]:
            fields['opt.%s'%m] = QtGui.QCheckBox(m)
            if c: fields['opt.%s'%m].setChecked(True)
            grid.addWidget(fields['opt.%s'%m],row,0)
            row+=1
        # Add Ok/Cancel
        box = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok|QtGui.QDialogButtonBox.Cancel)
        grid.addWidget(box,row,0,alignment=QtCore.Qt.AlignRight)
        box.accepted.connect(lambda *a,**k:not(fields["name"].text().isEmpty()) and self.__generate(diag,fields) or QtGui.QMessageBox.warning(diag,'Invalid','Please Enter A Class Name'))
        box.rejected.connect(diag.hide)
        # Show Dialog
        if diag.exec_():
            return str(fields['name'].text())+".java"
    def __generate(self,diag,fields):
        kw = {'user':getpass.getuser()}
        for field,widget in fields.iteritems():
            if isinstance(widget,(QtGui.QLineEdit,QtGui.QLabel)):
                kw[field]=str(widget.text())
            elif isinstance(widget,(QtGui.QCheckBox,QtGui.QRadioButton)):
                kw[field]=bool(widget.isChecked())
            elif isinstance(widget,(str,int,bool)):
                kw[field]=widget
        st = ""
        if kw['opt.Add JavaDoc']:
            st += str.format('''\
/**
* {CLASS}.java
* @author: {USER}
* @copyright: {YEAR} {USER}
* @since: {SINCE}
* @status: Development
* @version: 0.0-devel-{YYMMDD}-0
*/
''',CLASS=kw['name'],USER=kw['user'],YEAR=time.strftime("%Y"),SINCE=time.strftime('%d %b %y'),YYMMDD=time.strftime("%y%m%d"))
        if kw['package'].strip(): st+='package %s;\n'%kw['package']
        st += str.format("{VIS} interface {INTERFACE} ",
                         VIS=kw['vis.public'] and 'public ' or '', 
                         INTERFACE=kw['name'])
        st += "{\n}"
        self.write(os.path.join(kw['folder'],kw['name']+".java"), st)
        diag.hide()
        diag.accept()
        return True